package cn.dankal.flyaudio;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.LogUtils;
import com.facebook.stetho.common.LogUtil;
import com.google.gson.Gson;
import com.jeremyliao.liveeventbus.LiveEventBus;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import cn.dankal.basiclib.base.fragment.BaseFragment;
import cn.dankal.basiclib.common.bus.LiveDataBusConstants;
import cn.dankal.basiclib.pojo.GroupInvateCountBean;
import cn.dankal.basiclib.util.ActivityUtils;
import cn.dankal.basiclib.util.SharePreferenceManager;
import cn.dankal.basiclib.util.ToastUtils;
import cn.dankal.flyaudio.adapter.FriendAdapter;
import cn.dankal.flyaudio.chat.ConversationListHelper;
import cn.dankal.flyaudio.database.FriendEntry;
import cn.dankal.flyaudio.database.FriendRecommendEntry;
import cn.dankal.flyaudio.database.GroupApplyEntry;
import cn.dankal.flyaudio.database.UserEntry;
import cn.dankal.flyaudio.entity.Event;
import cn.dankal.flyaudio.entity.EventType;
import cn.dankal.flyaudio.entity.FriendInvitation;
import cn.dankal.flyaudio.entity.GroupApplyInvitation;
import cn.dankal.flyaudio.entity.PickContractPersonEntity;
import cn.dankal.flyaudio.friend.ContractPersonActivity;
import cn.dankal.flyaudio.friend.utils.pinyin.HanziToPinyin;
import cn.dankal.flyaudio.pop.FriendAddPop;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.callback.CreateGroupCallback;
import cn.jpush.im.android.api.callback.GetAvatarBitmapCallback;
import cn.jpush.im.android.api.callback.GetUserInfoCallback;
import cn.jpush.im.android.api.callback.GetUserInfoListCallback;
import cn.jpush.im.android.api.content.EventNotificationContent;
import cn.jpush.im.android.api.enums.ConversationType;
import cn.jpush.im.android.api.event.ContactNotifyEvent;
import cn.jpush.im.android.api.event.ConversationRefreshEvent;
import cn.jpush.im.android.api.event.GroupApprovalEvent;
import cn.jpush.im.android.api.event.MessageEvent;
import cn.jpush.im.android.api.event.MessageReceiptStatusChangeEvent;
import cn.jpush.im.android.api.event.MessageRetractEvent;
import cn.jpush.im.android.api.event.OfflineMessageEvent;
import cn.jpush.im.android.api.model.Conversation;
import cn.jpush.im.android.api.model.GroupInfo;
import cn.jpush.im.android.api.model.Message;
import cn.jpush.im.android.api.model.UserInfo;
import cn.jpush.im.api.BasicCallback;

public class FriendFragment extends BaseFragment implements View.OnClickListener {

    private static final int REFRESH_CONVERSATION_LIST = 0x3000;
    private static final int DISMISS_REFRESH_HEADER = 0x3001;
    private static final int ROAM_COMPLETED = 0x3002;

    private RecyclerView friendView;

    private FriendAdapter adapter;

    private ConversationListHelper controller = new ConversationListHelper();

    private BackgroundHandler mBackgroundHandler;

    private HandlerThread mThread;

    protected boolean isCreate = false;

    private TextView numView;

    private Conversation needToDeleteGroupConversation;


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_friend;
    }

    @Override
    public void onResume() {
        super.onResume();
        adapter.sortConvList();
        Log.e("FriendFragment","onResume "+isVisibleToUser);
        if(needToDeleteGroupConversation != null && adapter != null){
            Log.e("FriendFragment","onResume deleteConversation");
            adapter.deleteConversation(needToDeleteGroupConversation);
            needToDeleteGroupConversation = null;
        }

        //更新气泡中的数量和显示状态
        if(numView != null) {
            int showNum = SharePreferenceManager.getCachedNewGroupInvateNum();
            int newFriendNum = SharePreferenceManager.getCachedNewFriendNum();
            if (showNum + newFriendNum > 0) {
                numView.setVisibility(View.VISIBLE);
                numView.setText(String.valueOf(showNum + newFriendNum));
            } else {
                numView.setVisibility(View.GONE);
            }
        }
    }

    @Override
    protected void initComponents() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        friendView = getView().findViewById(R.id.rv_friend);
        adapter = new FriendAdapter();
        numView = getView().findViewById(R.id.tv_system_public_number);
        controller.initConvListAdapter();
        mThread = new HandlerThread("MainActivity");
        mThread.start();
        mBackgroundHandler = new BackgroundHandler(mThread.getLooper());
        friendView.setLayoutManager(new LinearLayoutManager(getContext()));
        friendView.setAdapter(adapter);
        getView().findViewById(R.id.iv_friend_add).setOnClickListener(this);
        getView().findViewById(R.id.iv_contract).setOnClickListener(this);
        adapter.addDatas(controller.getConversations(), true);
        adapter.addData(controller.getSettingConversation());
        adapter.sortConvList();
        if (SharePreferenceManager.getCachedNewFriendNum() > 0 || SharePreferenceManager.getCachedNewGroupInvateNum() > 0) {
            numView.setText(String.valueOf(SharePreferenceManager.getCachedNewFriendNum() + SharePreferenceManager.getCachedNewGroupInvateNum()));
            numView.setVisibility(View.VISIBLE);
        } else {
            numView.setVisibility(View.GONE);
        }
        LiveEventBus.get(LiveDataBusConstants.GROUP_MESSAGE_SET_TOP, Conversation.class).observe(this, new Observer<Conversation>() {
            @Override
            public void onChanged(Conversation conversation) {
                LogUtils.e("GROUP_MESSAGE_SET_TOP");
                adapter.setConvTop(conversation);
            }
        });
        LiveEventBus.get(LiveDataBusConstants.GROUP_MESSAGE_CANCEL_SET_TOP, Conversation.class).observe(this, new Observer<Conversation>() {
            @Override
            public void onChanged(Conversation conversation) {
                LogUtils.e("GROUP_MESSAGE_CANCEL_SET_TOP");
                adapter.setCancelConvTop(conversation);

            }
        });
        LiveEventBus.get(LiveDataBusConstants.REFRESH_CONV_LIST, String.class).observe(this, new Observer<String>() {
            @Override
            public void onChanged(String conversation) {
                LogUtils.e("REFRESH_CONV_LIST");
                controller.initConvListAdapter();
                adapter.addDatas(controller.getConversations(), true);
                adapter.addData(controller.getSettingConversation());
                adapter.sortConvList();
            }
        });
        LiveEventBus.get(LiveDataBusConstants.PRIVATE_MESSAGE_SET_TOP, Conversation.class).observe(this, new Observer<Conversation>() {
            @Override
            public void onChanged(Conversation conversation) {
                LogUtils.e("PRIVATE_MESSAGE_SET_TOP");
                adapter.setConvTop(conversation);
            }
        });
        LiveEventBus.get(LiveDataBusConstants.PRIVATE_MESSAGE_CANCEL_SET_TOP, Conversation.class).observe(this, new Observer<Conversation>() {
            @Override
            public void onChanged(Conversation conversation) {
                LogUtils.e("PRIVATE_MESSAGE_CANCEL_SET_TOP");
                adapter.setCancelConvTop(conversation);
            }
        });
        LiveEventBus.get("pick_contract_person", PickContractPersonEntity.class).observe(this, new Observer<PickContractPersonEntity>() {
            @Override
            public void onChanged(PickContractPersonEntity pickContractPersonEntity) {
                LogUtils.e("pick_contract_person");
                List<String> username = pickContractPersonEntity.getUserInfos();
                StringBuilder groupName = new StringBuilder();
                groupName.append(JMessageClient.getMyInfo().getUserName());
                groupName.append(",");
                for (String userInfo : username) {
                    groupName.append(userInfo);
                    groupName.append(",");
                }
                JMessageClient.createPublicGroup(groupName.toString(), "测试", new CreateGroupCallback() {
                    @Override
                    public void gotResult(int resopnseCode, String s, long l) {
                        if (resopnseCode == 0) {
                            ToastUtils.showShort("创建群组成功");
                            JMessageClient.addGroupMembers(l, FlyApplication.JPUSH_KEY, username, new BasicCallback() {
                                @Override
                                public void gotResult(int i, String s) {
                                    Log.d("PickContractPerson", JSON.toJSONString(username));
                                }
                            });
                        } else {
                            ToastUtils.showShort("创建群组失败:" + s);
                        }
                    }
                });
            }
        });
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(Event event) {
        Log.d("FriendFragment", "收到消息OnEvent:" + event.getType());
        switch (event.getType()) {
            case createConversation:
                Conversation conv = event.getConversation();
                if (conv != null) {
                    adapter.addNewConversation(conv);
                }
                break;
            case deleteConversation:
                conv = event.getConversation();
                if (null != conv) {
//                    if(isVisibleToUser) {
                    if(adapter!=null) {
                        adapter.deleteConversation(conv);
                    }
//                    }else{
                        needToDeleteGroupConversation = conv;
//                    }
                }
                break;
            //收到保存为草稿事件
            case draft:
//                conv = event.getConversation();
//                String draft = event.getDraft();
//                //如果草稿内容不为空，保存，并且置顶该会话
//                if (!TextUtils.isEmpty(draft)) {
//                    adapter.putDraftToMap(conv, draft);
//                    adapter.setToTop(conv);
//                    //否则删除
//                } else {
//                    adapter.delDraftFromMap(conv);
//                }
                break;
            case addFriend:
                break;
            case refreshConversationList:
                controller.initConvListAdapter();
                break;
        }
    }

    //群主收到群组验证事件
    public void onEvent(GroupApprovalEvent event) {
        Log.d("FriendFrgment", "onEvent(GroupApprovalEvent event) json = "+JSON.toJSONString(event));
        final UserEntry user = FlyApplication.getUserEntry();
        GroupApprovalEvent.Type type = event.getType();
        long gid = event.getGid();
        event.getFromUserInfo(new GetUserInfoCallback() {
            @Override
            public void gotResult(int i, String s, UserInfo fromUserInfo) {
                if (i == 0) {
                    Gson gson = new Gson();
                    event.getApprovalUserInfoList(new GetUserInfoListCallback() {
                        @Override
                        public void gotResult(int i, String s, List<UserInfo> list) {
                            if (i == 0) {
                                if (FlyApplication.forAddIntoGroup.size() > 0) {
                                    for (String addName : FlyApplication.forAddIntoGroup) {
                                        if (addName.equals(list.get(0).getUserName())) {
                                            return;
                                        } else {
                                            FlyApplication.forAddIntoGroup.add(list.get(0).getUserName());
                                        }
                                    }
                                }
                                GroupApplyEntry entry;
                                //邀请,from是邀请方
                                if (type.equals(GroupApprovalEvent.Type.invited_into_group)) {
                                    entry = GroupApplyEntry.getEntry(user, list.get(0).getUserName(), list.get(0).getAppKey());
                                    if (entry != null) {
                                        entry.delete();
                                    }
                                    if (fromUserInfo.getAvatar() != null) {
                                        entry = new GroupApplyEntry(fromUserInfo.getUserName(), list.get(0).getUserName(), fromUserInfo.getAppKey(),
                                                list.get(0).getAvatarFile().getPath(), fromUserInfo.getDisplayName(), list.get(0).getDisplayName(),
                                                null, GroupApplyInvitation.INVITED.getValue(), gson.toJson(event), gid + "",
                                                user, 0, 0);//邀请type=0
                                    } else {
                                        entry = new GroupApplyEntry(fromUserInfo.getUserName(), list.get(0).getUserName(), fromUserInfo.getAppKey(),
                                                null, fromUserInfo.getDisplayName(), list.get(0).getDisplayName(),
                                                null, GroupApplyInvitation.INVITED.getValue(), gson.toJson(event), gid + "",
                                                user, 0, 0);//邀请type=0
                                    }
                                } else {
                                    entry = GroupApplyEntry.getEntry(user, fromUserInfo.getUserName(), fromUserInfo.getAppKey());
                                    if (entry != null) {
                                        entry.delete();
                                    }
                                    if (fromUserInfo.getAvatar() != null) {
                                        entry = new GroupApplyEntry(list.get(0).getUserName(), list.get(0).getUserName(), list.get(0).getAppKey(),
                                                list.get(0).getAvatarFile().getPath(), list.get(0).getDisplayName(), list.get(0).getDisplayName(),
                                                event.getReason(), GroupApplyInvitation.INVITED.getValue(), gson.toJson(event), gid + "",
                                                user, 0, 1);//申请type=1
                                    } else {
                                        entry = new GroupApplyEntry(list.get(0).getUserName(), list.get(0).getUserName(), list.get(0).getAppKey(),
                                                null, fromUserInfo.getDisplayName(), list.get(0).getDisplayName(),
                                                event.getReason(), GroupApplyInvitation.INVITED.getValue(), gson.toJson(event), gid + "",
                                                user, 0, 1);//申请type=1
                                    }
                                }
                                entry.save();

                                GroupInvateCountBean invateCountBean = new GroupInvateCountBean();
                                invateCountBean.gid = gid;
                                invateCountBean.count = 1;
                                SharePreferenceManager.addCachedNewGroupInvate(invateCountBean);
                                int showNum = SharePreferenceManager.getCachedNewGroupInvateNum();
                                int newFriendNum = SharePreferenceManager.getCachedNewFriendNum();
                                if (showNum + newFriendNum != 0) {
                                    numView.setVisibility(View.VISIBLE);
                                    numView.setText(showNum + "");
                                } else {
                                    numView.setVisibility(View.GONE);
                                }
//                        mAllContactNumber.setVisibility(View.VISIBLE);
//                        mAllContactNumber.setText(String.valueOf(showNum));
//                                SharePreferenceManager.setCachedNewGroupNum(showNum);
                            }
                        }
                    });

                }
            }
        });
    }

    //接收到好友事件
    public void onEvent(ContactNotifyEvent event) {
        Log.d("FriendFrgment", "onEvent(ContactNotifyEvent event) json = "+JSON.toJSONString(event));
        final UserEntry user = FlyApplication.getUserEntry();
        final String reason = event.getReason();
        final String username = event.getFromUsername();
        final String appKey = event.getfromUserAppKey();
        //对方接收了你的好友请求
        if (event.getType() == ContactNotifyEvent.Type.invite_accepted) {
            JMessageClient.getUserInfo(username, appKey, new GetUserInfoCallback() {
                @Override
                public void gotResult(int responseCode, String responseMessage, UserInfo info) {
                    if (responseCode == 0) {
                        String name = info.getNickname();
                        if (TextUtils.isEmpty(name)) {
                            name = info.getUserName();
                        }
                        FriendEntry friendEntry = FriendEntry.getFriend(user, username, appKey);
                        if (friendEntry == null) {
                            final FriendEntry newFriend = new FriendEntry(info.getUserID(), username, info.getNotename(), info.getNickname(), appKey, info.getAvatar(), name, getLetter(name), user);
                            newFriend.save();
                        }
                    }
                }
            });
            FriendRecommendEntry entry = FriendRecommendEntry.getEntry(user, username, appKey);
            entry.state = FriendInvitation.ACCEPTED.getValue();
            entry.save();

            Conversation conversation = JMessageClient.getSingleConversation(username);
            if (conversation == null) {
                conversation = Conversation.createSingleConversation(username);
                EventBus.getDefault().post(new Event.Builder()
                        .setType(EventType.createConversation)
                        .setConversation(conversation)
                        .build());
            }

            //拒绝好友请求
        } else if (event.getType() == ContactNotifyEvent.Type.invite_declined) {
            FlyApplication.forAddFriend.remove(username);
            FriendRecommendEntry entry = FriendRecommendEntry.getEntry(user, username, appKey);
            entry.state = FriendInvitation.BE_REFUSED.getValue();
            entry.reason = reason;
            entry.save();
            //收到好友邀请
        } else if (event.getType() == ContactNotifyEvent.Type.invite_received) {
            //如果同一个人申请多次,则只会出现一次;当点击进验证消息界面后,同一个人再次申请则可以收到
            if (FlyApplication.forAddFriend.size() > 0) {
                for (String forAdd : FlyApplication.forAddFriend) {
                    if (forAdd.equals(username)) {
                        return;
                    } else {
                        FlyApplication.forAddFriend.add(username);
                    }
                }
            } else {
                FlyApplication.forAddFriend.add(username);
            }
            JMessageClient.getUserInfo(username, appKey, new GetUserInfoCallback() {
                @Override
                public void gotResult(int status, String desc, UserInfo userInfo) {
                    if (status == 0) {
                        String name = userInfo.getNickname();
                        if (TextUtils.isEmpty(name)) {
                            name = userInfo.getUserName();
                        }
                        FriendRecommendEntry entry = null;
                        try {
                            entry = FriendRecommendEntry.getEntry(user, username, appKey);
                        } catch (Exception e) {
                            Log.d("FriendFragment", "error-" + e.getLocalizedMessage());
                        }
                        if (null == entry) {
                            if (null != userInfo.getAvatar()) {
                                String path = userInfo.getAvatarFile().getPath();
                                entry = new FriendRecommendEntry(userInfo.getUserID(), username, userInfo.getNotename(), userInfo.getNickname(), appKey, path,
                                        name, reason, FriendInvitation.INVITED.getValue(), user, 0);
                            } else {
                                entry = new FriendRecommendEntry(userInfo.getUserID(), username, userInfo.getNotename(), userInfo.getNickname(), appKey, null,
                                        username, reason, FriendInvitation.INVITED.getValue(), user, 0);
                            }
                        } else {
                            entry.state = FriendInvitation.INVITED.getValue();
                            entry.reason = reason;
                        }
                        entry.save();
                        //收到好友请求数字 +1
                        int showNum = SharePreferenceManager.getCachedNewFriendNum() + 1;
                        int newGroupNum = SharePreferenceManager.getCachedNewGroupInvateNum();
                        if (showNum + newGroupNum != 0) {
                            numView.setVisibility(View.VISIBLE);
                            numView.setText(showNum + "");
                        } else {
                            numView.setVisibility(View.GONE);
                        }
//                        mAllContactNumber.setVisibility(View.VISIBLE);
//                        mAllContactNumber.setText(String.valueOf(showNum));
                        SharePreferenceManager.setCachedNewFriendNum(showNum);
                    }
                }
            });
        } else if (event.getType() == ContactNotifyEvent.Type.contact_deleted) {


            Conversation conversation = JMessageClient.getSingleConversation(username);
            if (conversation != null) {
//                conversation = Conversation.createSingleConversation(username);
                EventBus.getDefault().post(new Event.Builder().setType(EventType.deleteConversation)
                        .setConversation(conversation)
                        .build());
            }

            FlyApplication.forAddFriend.remove(username);
            FriendRecommendEntry friendEntry = FriendRecommendEntry.getEntry(user, username, appKey);
            friendEntry.delete();
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        JMessageClient.registerEventReceiver(this);
    }

    @Override
    public void onDestroy() {
        JMessageClient.unRegisterEventReceiver(this);
        if (mBackgroundHandler != null) {
            mBackgroundHandler.removeCallbacksAndMessages(null);
        }
        if (mThread != null) {
            mThread.getLooper().quit();
        }
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (R.id.iv_friend_add == id) {
            new FriendAddPop(getContext()).showPopupWindow(R.id.iv_friend_add);
        } else if (R.id.iv_contract == id) {
            ActivityUtils.startActivity(ContractPersonActivity.class);
        }
    }

    private String getLetter(String name) {
        String letter;
        ArrayList<HanziToPinyin.Token> tokens = HanziToPinyin.getInstance()
                .get(name);
        StringBuilder sb = new StringBuilder();
        if (tokens != null && tokens.size() > 0) {
            for (HanziToPinyin.Token token : tokens) {
                if (token.type == HanziToPinyin.Token.PINYIN) {
                    sb.append(token.target);
                } else {
                    sb.append(token.source);
                }
            }
        }
        String sortString = sb.toString().substring(0, 1).toUpperCase();
        if (sortString.matches("[A-Z]")) {
            letter = sortString.toUpperCase();
        } else {
            letter = "#";
        }
        return letter;
    }

    /**
     * 收到消息
     */
    public void onEvent(MessageEvent event) {
        Log.d("FriendFragment", "收到消息MessageEvent");

        Message msg = event.getMessage();
        Log.e("FriendFragment", msg.getTargetType() + "");
        if (msg.getTargetType() == ConversationType.group) {
            long groupId = ((GroupInfo) msg.getTargetInfo()).getGroupID();
            Conversation conv = JMessageClient.getGroupConversation(groupId);
            if (conv != null && controller != null) {
                if (msg.isAtMe()) {
                    FlyApplication.isAtMe.put(groupId, true);
                    adapter.putAtConv(conv, msg.getId());
                }
                if (msg.isAtAll()) {
                    FlyApplication.isAtall.put(groupId, true);
                    adapter.putAtAllConv(conv, msg.getId());
                }

                if (msg.getContent() instanceof EventNotificationContent) {
                    EventNotificationContent c = (EventNotificationContent) msg.getContent();
                    if (c.getEventNotificationType() == EventNotificationContent.EventNotificationType.group_dissolved) {

                    } else {
                        mBackgroundHandler.sendMessageDelayed(mBackgroundHandler.obtainMessage(REFRESH_CONVERSATION_LIST,
                                conv),1000);
                    }
                } else {
                    mBackgroundHandler.sendMessage(mBackgroundHandler.obtainMessage(REFRESH_CONVERSATION_LIST,
                            conv));
                }
            }
        } else {
            final UserInfo userInfo = (UserInfo) msg.getTargetInfo();
            String targetId = userInfo.getUserName();
            Conversation conv = JMessageClient.getSingleConversation(targetId, userInfo.getAppKey());
            adapter.setToTop(conv);

            if (conv != null && controller != null) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (TextUtils.isEmpty(userInfo.getAvatar())) {
                            userInfo.getAvatarBitmap(new GetAvatarBitmapCallback() {
                                @Override
                                public void gotResult(int responseCode, String responseMessage, Bitmap avatarBitmap) {
                                    if (responseCode == 0) {
                                        adapter.notifyDataSetChanged();
                                    }
                                }
                            });
                        }
                    }
                });
                mBackgroundHandler.sendMessage(mBackgroundHandler.obtainMessage(REFRESH_CONVERSATION_LIST, conv));
            }
        }
    }

    /**
     * 接收离线消息
     *
     * @param event 离线消息事件
     */
    public void onEvent(OfflineMessageEvent event) {
        Conversation conv = event.getConversation();
        if (!conv.getTargetId().equals("feedback_Android") && conv.getType() != ConversationType.chatroom) {
            mBackgroundHandler.sendMessage(mBackgroundHandler.obtainMessage(REFRESH_CONVERSATION_LIST, conv));
        }
    }

    /**
     * 消息撤回
     */
    public void onEvent(MessageRetractEvent event) {
        Conversation conversation = event.getConversation();
        mBackgroundHandler.sendMessage(mBackgroundHandler.obtainMessage(REFRESH_CONVERSATION_LIST, conversation));
    }

    /**
     * 消息已读事件
     */
    public void onEventMainThread(MessageReceiptStatusChangeEvent event) {
        adapter.notifyDataSetChanged();
    }

    /**
     * 消息漫游完成事件
     *
     * @param event 漫游完成后， 刷新会话事件
     */
    public void onEvent(ConversationRefreshEvent event) {
        Log.d("FriendFragment", "消息漫游");
        Conversation conv = event.getConversation();
        if (!conv.getTargetId().equals("feedback_Android") && conv.getType() != ConversationType.chatroom) {
            mBackgroundHandler.sendMessage(mBackgroundHandler.obtainMessage(REFRESH_CONVERSATION_LIST, conv));
            //多端在线未读数改变时刷新
            if (event.getReason().equals(ConversationRefreshEvent.Reason.UNREAD_CNT_UPDATED)) {
                mBackgroundHandler.sendMessage(mBackgroundHandler.obtainMessage(REFRESH_CONVERSATION_LIST, conv));
            }
        }
    }

    private class BackgroundHandler extends Handler {
        public BackgroundHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case REFRESH_CONVERSATION_LIST:
                    Conversation conv = (Conversation) msg.obj;
                    LogUtil.e(conv.getTitle(), conv.getType());
                    if (conv.getType() != ConversationType.chatroom) {
                        adapter.setToTop(conv);
                    }
                    break;
                case DISMISS_REFRESH_HEADER:
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
//                            mConvListView.dismissLoadingHeader();
                        }
                    });
                    break;
                case ROAM_COMPLETED:
                    conv = (Conversation) msg.obj;
                    adapter.addAndSort(conv);
                    break;
            }
        }
    }

}
